package com.hadoop.exam;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;

/**
 * 
 * @author Archie
 *	forth question
 */
public class Test_IO {
	
// output 
	File file =new File("D:/Test/write.txt");
	public void write() {
		
		if(!file.exists()) {
			String path = file.getPath();
			String route=path.substring(0,path.lastIndexOf("\\"));
			File filePath =new File(route);
			if(filePath.isDirectory() && filePath.exists()) {
				try {
					file.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			else {
				filePath.mkdirs();
				try {
					file.createNewFile();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
		}
		OutputStream out;
		try {
			out = new FileOutputStream(file);
			String str = "我叫刘渴望\n我是参加北风网入班测试的学生";
			//String encodingStr = new String(str.getBytes("GBK"),"utf-8");
			byte[] bytes =str.getBytes();
			out.write(bytes);
			out.flush();
			out.close();
			System.out.println("write completely");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public void read() {
		if(!file.exists()) {
			System.out.println("该文件不存在");
		}
		try {
			//InputStream inputStream = new FileInputStream(file);
			//byte[] bytes =new byte[(int) file.length()];
			/*inputStream.read(bytes);
			inputStream.close();
			String content = new String(bytes,"UTF-8");*/
			Reader reader =new FileReader(file.getPath());
			BufferedReader bufferedReader = new BufferedReader(reader);
			int i = 1 ;
			while(bufferedReader.ready()) {
				System.out.println("line "+ i++ +":" +bufferedReader.readLine());
			}	
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
class LiuKeWang4 {
	
	public static void main(String[] args) {
		Test_IO test =new Test_IO();
		test.write();
		test.read();
	}

}
